<template>
  <view class="attendance-container">
    <!-- 本月统计 -->
    <view class="stat-card">
      <view class="stat-header">
        <text class="title">本月考勤统计</text>
        <text class="date">{{ currentMonth }}</text>
      </view>
      <view class="stat-content">
        <view class="stat-item">
          <text class="label">出勤天数</text>
          <text class="value">{{ monthStat.totalDays || 0 }}天</text>
        </view>
        <view class="stat-item">
          <text class="label">工作时长</text>
          <text class="value">{{ monthStat.totalHours || 0 }}小时</text>
        </view>
      </view>
    </view>

    <!-- 日历视图 -->
    <view class="calendar-card">
      <view class="calendar-header">
        <text class="prev-month" @tap="changeMonth(-1)">◀</text>
        <text class="current-month">{{ currentMonth }}</text>
        <text class="next-month" @tap="changeMonth(1)">▶</text>
      </view>
      <view class="weekdays">
        <text v-for="day in ['日', '一', '二', '三', '四', '五', '六']" :key="day">{{ day }}</text>
      </view>
      <view class="days">
        <view 
          v-for="(day, index) in calendarDays" 
          :key="index"
          class="day"
          :class="{
            'other-month': !day.currentMonth,
            'has-record': day.hasRecord,
            'today': day.isToday,
            'type-1': day.type === 1,
            'type-2': day.type === 2,
            'type-3': day.type === 3
          }"
          @tap="showDayDetail(day)"
        >
          <text class="date">{{ day.date }}</text>
          <text v-if="day.hasRecord" class="record-type">{{ getTypeText(day.type) }}</text>
        </view>
      </view>
    </view>

    <!-- 考勤记录列表 -->
    <view class="records-card">
      <view class="records-header">
        <text class="title">考勤记录</text>
      </view>
      <view class="records-list">
        <view 
          v-for="record in records" 
          :key="record.id"
          class="record-item"
          :class="'type-' + record.type"
        >
          <view class="record-main">
            <text class="date">{{ formatDate(record.date) }}</text>
            <text class="type">{{ getFullTypeText(record.type) }}</text>
          </view>
          <view class="record-detail">
            <text class="hours">{{ record.workHours }}小时</text>
            <text v-if="record.remark" class="remark">{{ record.remark }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 日期详情弹窗 -->
    <uni-popup ref="dayDetailPopup" type="center">
      <view class="detail-popup">
        <view class="popup-header">
          <text class="title">考勤详情</text>
          <text class="close" @tap="closeDayDetail">×</text>
        </view>
        <view class="popup-content" v-if="selectedDayRecord">
          <view class="detail-item">
            <text class="label">日期：</text>
            <text class="value">{{ formatFullDate(selectedDayRecord.date) }}</text>
          </view>
          <view class="detail-item">
            <text class="label">考勤类型：</text>
            <text class="value">{{ getFullTypeText(selectedDayRecord.type) }}</text>
          </view>
          <view class="detail-item">
            <text class="label">工作时长：</text>
            <text class="value">{{ selectedDayRecord.workHours }}小时</text>
          </view>
          <view class="detail-item" v-if="selectedDayRecord.remark">
            <text class="label">备注：</text>
            <text class="value">{{ selectedDayRecord.remark }}</text>
          </view>
        </view>
        <view class="popup-footer">
          <button class="close-btn" @tap="closeDayDetail">关闭</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import dayjs from 'dayjs'
import attendance from '@/api/attendance'

// 状态
const selectedDate = ref(dayjs())
const monthStat = ref({})
const records = ref([])
const selectedDayRecord = ref(null)
const dayDetailPopup = ref(null)

// 计算属性
const currentMonth = computed(() => {
  return selectedDate.value.format('YYYY年MM月')
})

const calendarDays = computed(() => {
  const date = selectedDate.value
  const firstDay = date.startOf('month')
  const lastDay = date.endOf('month')
  
  // 获取日历开始日期（上月最后几天）
  const startDate = firstDay.day(0) // 从周日开始
  
  const days = []
  let currentDate = startDate
  
  // 生成6周的日历数据
  for (let i = 0; i < 42; i++) {
    const isCurrentMonth = currentDate.month() === date.month()
    const recordForDay = records.value.find(r => 
      dayjs(r.date).format('YYYY-MM-DD') === currentDate.format('YYYY-MM-DD')
    )
    
    days.push({
      date: currentDate.date(),
      currentMonth: isCurrentMonth,
      isToday: currentDate.format('YYYY-MM-DD') === dayjs().format('YYYY-MM-DD'),
      hasRecord: !!recordForDay,
      type: recordForDay?.type,
      fullDate: currentDate.format('YYYY-MM-DD'),
      record: recordForDay
    })
    
    currentDate = currentDate.add(1, 'day')
  }
  
  return days
})

// 方法
function getTypeText(type) {
  const types = {
    1: '全',
    2: '半',
    3: '加'
  }
  return types[type] || ''
}

function getFullTypeText(type) {
  const types = {
    1: '全天班',
    2: '半天班',
    3: '小时工'
  }
  return types[type] || ''
}

function formatDate(date) {
  return dayjs(date).format('MM-DD')
}

function formatFullDate(date) {
  return dayjs(date).format('YYYY年MM月DD日')
}

function changeMonth(offset) {
  selectedDate.value = selectedDate.value.add(offset, 'month')
  fetchMonthRecords()
}

// 获取本月考勤记录
async function fetchMonthRecords() {
  try {
    const startTime = selectedDate.value.startOf('month').format('YYYY-MM-DD 00:00:00')
    const endTime = selectedDate.value.endOf('month').format('YYYY-MM-DD 23:59:59')
    
    const res = await attendance.getList({
      startTime,
      endTime
    })
    
    if (res && res.records) {
      records.value = res.records
      monthStat.value = {
        totalDays: res.totalDays || 0,
        totalHours: res.totalHours || 0
      }
    }
  } catch (error) {
    console.error('获取考勤记录失败:', error)
    uni.showToast({
      title: '获取考勤记录失败',
      icon: 'none'
    })
  }
}

// 显示日期详情
function showDayDetail(day) {
  if (!day.hasRecord) return
  selectedDayRecord.value = day.record
  dayDetailPopup.value.open()
}

// 关闭日期详情
function closeDayDetail() {
  dayDetailPopup.value.close()
  selectedDayRecord.value = null
}

// 页面加载
onMounted(() => {
  fetchMonthRecords()
})
</script>

<style lang="scss">
.attendance-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
  
  .stat-card {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
    
    .stat-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;
      
      .title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .date {
        font-size: 28rpx;
        color: #666;
      }
    }
    
    .stat-content {
      display: flex;
      justify-content: space-around;
      
      .stat-item {
        text-align: center;
        
        .label {
          font-size: 28rpx;
          color: #666;
          margin-bottom: 10rpx;
          display: block;
        }
        
        .value {
          font-size: 40rpx;
          color: #1296db;
          font-weight: bold;
        }
      }
    }
  }
  
  .calendar-card {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
    
    .calendar-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;
      
      .current-month {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .prev-month,
      .next-month {
        font-size: 32rpx;
        color: #666;
        padding: 10rpx 20rpx;
        
        &:active {
          opacity: 0.7;
        }
      }
    }
    
    .weekdays {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      text-align: center;
      margin-bottom: 20rpx;
      
      text {
        font-size: 28rpx;
        color: #666;
      }
    }
    
    .days {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 10rpx;
      
      .day {
        aspect-ratio: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        border-radius: 10rpx;
        position: relative;
        
        &.other-month {
          opacity: 0.3;
        }
        
        &.has-record {
          background-color: rgba(18, 150, 219, 0.1);
          
          &.type-1 {
            background-color: rgba(82, 196, 26, 0.1);
            .date { color: #52c41a; }
          }
          
          &.type-2 {
            background-color: rgba(250, 173, 20, 0.1);
            .date { color: #faad14; }
          }
          
          &.type-3 {
            background-color: rgba(24, 144, 255, 0.1);
            .date { color: #1890ff; }
          }
        }
        
        &.today {
          background-color: #1296db;
          
          .date,
          .record-type {
            color: #fff !important;
          }
        }
        
        .date {
          font-size: 28rpx;
          color: #333;
        }
        
        .record-type {
          font-size: 20rpx;
          margin-top: 4rpx;
          
          &.type-1 { color: #52c41a; }
          &.type-2 { color: #faad14; }
          &.type-3 { color: #1890ff; }
        }
      }
    }
  }
  
  .records-card {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
    
    .records-header {
      margin-bottom: 30rpx;
      
      .title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
    }
    
    .records-list {
      .record-item {
        padding: 20rpx;
        border-radius: 12rpx;
        margin-bottom: 20rpx;
        border-left: 6rpx solid #eee;
        
        &.type-1 {
          background-color: rgba(82, 196, 26, 0.1);
          border-left-color: #52c41a;
        }
        
        &.type-2 {
          background-color: rgba(250, 173, 20, 0.1);
          border-left-color: #faad14;
        }
        
        &.type-3 {
          background-color: rgba(24, 144, 255, 0.1);
          border-left-color: #1890ff;
        }
        
        .record-main {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10rpx;
          
          .date {
            font-size: 28rpx;
            color: #333;
          }
          
          .type {
            font-size: 28rpx;
            font-weight: bold;
          }
        }
        
        .record-detail {
          display: flex;
          justify-content: space-between;
          
          .hours {
            font-size: 24rpx;
            color: #666;
          }
          
          .remark {
            font-size: 24rpx;
            color: #999;
          }
        }
      }
    }
  }
  
  .detail-popup {
    background-color: #fff;
    border-radius: 20rpx;
    width: 600rpx;
    
    .popup-header {
      padding: 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .title {
        font-size: 32rpx;
        font-weight: bold;
      }
      
      .close {
        font-size: 40rpx;
        color: #999;
        padding: 10rpx;
      }
    }
    
    .popup-content {
      padding: 30rpx;
      
      .detail-item {
        margin-bottom: 20rpx;
        
        .label {
          color: #666;
          margin-right: 20rpx;
        }
        
        .value {
          color: #333;
          font-weight: bold;
        }
      }
    }
    
    .popup-footer {
      padding: 30rpx;
      border-top: 1rpx solid #f5f5f5;
      
      .close-btn {
        background-color: #f5f5f5;
        color: #333;
        height: 80rpx;
        line-height: 80rpx;
        border-radius: 40rpx;
        font-size: 28rpx;
      }
    }
  }
}
</style> 